package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.qiantu.api.entity.SmsBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.PermissionsConfirmDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.utils.StringUtil;
import com.qiantu.phone.widget.EditTextLayout;
import com.qiantu.phone.widget.viewmodel.PasswordLoginPresenter;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class LoginActivity extends AppActivity{
    private static final String INTENT_KEY_IN_PHONE = "phone";
    private static final String INTENT_KEY_IN_PASSWORD = "password";

    @Log
    public static void start(Context context, String phone, String password) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(INTENT_KEY_IN_PHONE, "");
        intent.putExtra(INTENT_KEY_IN_PASSWORD, "");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Log
    public static void startFromLogOff(Context context, boolean showLogoffDialog) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("showLogoffDialog", showLogoffDialog);
        context.startActivity(intent);
    }

    @Log
    public static void startFromChangeAccount(Context context, boolean isChangeAccount) {
        Intent intent = new Intent(context, LoginActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("isChangeAccount", isChangeAccount);
        context.startActivity(intent);
    }

    private EditTextLayout mEdtAccount;
    private TextView mErrorHint;
    private View mBtnGetCode;
    public CheckBox agreeCheckBox;
    private PasswordLoginPresenter passwordLoginPresenter;

    /** logo 缩放比例 */
    private final float mLogoScale = 0.8f;
    /** 动画时间 */
    private final int mAnimTime = 300;

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        overridePendingTransition(R.anim.anim_fade_in,R.anim.anim_fade_out);
        passwordLoginPresenter = new PasswordLoginPresenter(this, R.id.pwd_login_ly);
        mBtnGetCode = findViewById(R.id.btn_get_code);
        mEdtAccount = findViewById(R.id.edt_account);
        mErrorHint = findViewById(R.id.tv_error_hint);
        agreeCheckBox = findViewById(R.id.agree_check_box);
        TextView mPhoneNotAvailable = findViewById(R.id.tv_phone_not_available);
        //mPhoneNotAvailable.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        //mPhoneNotAvailable.getPaint().setAntiAlias(true);//抗锯齿
        setOnClickListener(mBtnGetCode, mPhoneNotAvailable);
        setOnClickListener(R.id.tv_user_agreement, R.id.tv_privacy_policy, R.id.pwd_login_text,R.id.change_service);
        mEdtAccount.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11){
                    if (StringUtil.isPhoneLegal(mEdtAccount.getText().toString())){
                        mBtnGetCode.setEnabled(agreeCheckBox.isChecked());
                    }else {
                        mEdtAccount.setSelected(true);
                        mBtnGetCode.setEnabled(false);
                        mErrorHint.setText(R.string.phone_error_hint);
                        mEdtAccount.setIconVisible(false);
                    }
                }else {
                    mBtnGetCode.setEnabled(false);
                    mEdtAccount.setSelected(false);
                    mErrorHint.setText("");
                    mEdtAccount.setIconVisible(true);
                }
            }
        });
        mEdtAccount.setText(AppApplication.getInstance().getUserPhone());
        agreeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    mBtnGetCode.setEnabled(StringUtil.isPhoneLegal(mEdtAccount.getText().toString()));
                }else{
                    mBtnGetCode.setEnabled(false);
                }
                if(passwordLoginPresenter.itemView.getVisibility() == View.VISIBLE){
                    passwordLoginPresenter.setBtnEnable();
                }
            }
        });
//        PermissionsConfirmDialog.Builder permissionsConfirmDialogBuilder = new PermissionsConfirmDialog.Builder(getActivity());
//        if(!permissionsConfirmDialogBuilder.isHasAllPermissions()){
//            permissionsConfirmDialogBuilder.create().show();
//        }
    }

    @Override
    protected void initData() {
        showLogoffDialog();
        fromChangeAccount();
    }

    private void fromChangeAccount() {
        if (getBoolean("isChangeAccount")){
            getTitleBar().setVisibility(View.VISIBLE);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_get_code:
                if (!StringUtil.isPhoneLegal(mEdtAccount.getText().toString())) {
                    mEdtAccount.setSelected(true);
                    mErrorHint.setText(R.string.phone_error_hint);
                    return;
                }
                if(!agreeCheckBox.isChecked()){
                    toast(R.string.agree_privacy);
                   return;
                }
                mEdtAccount.setSelected(false);
                showDialog();
                Map<String, Object> data = new HashMap<>();
                data.put("mobile", mEdtAccount.getText().toString());
                data.put("smsType", "login_boyun");
                // 隐藏软键盘
                hideKeyboard(getCurrentFocus());
                LLHttpManager.sendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
                    @Override
                    public void onStart(Call call) {
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }

                    @Override
                    public void onSucceed(HttpData<SmsBean> data) {
                        if(data.isRequestSucceed()){
                            toast(R.string.sms_code_send);
                            postDelayed(() -> {
                                // 跳转到验证码界面
                                CaptchaActivity.start(LoginActivity.this, mEdtAccount.getText().toString(), "login", data.getData().getSmsID());
                            }, 600);
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
                break;
            case R.id.tv_phone_not_available:
                PhoneAppealActivity.start(this);
                break;
            case R.id.tv_user_agreement:
                BrowserActivity.start(this, "https://sv-center.qiantu-iot.com/privacy/index_boyun.html");
                break;
            case R.id.tv_privacy_policy:
                BrowserActivity.start(this, "https://sv-center.qiantu-iot.com/privacy/privacy-policy.html");
                break;
            case R.id.pwd_login_text:
                changeLoginType(false);
                break;
            case R.id.change_service:
                Intent intent = new Intent(getContext(), PrivateCloudActivity.class);
                getContext().startActivity(intent);
                break;
        }
    }

    public void changeLoginType(boolean ver){
        if (ver){
            findViewById(R.id.ver_login_ly).setVisibility(View.VISIBLE);
//            vTTT.setText(R.string.login_ttt_ver);
            passwordLoginPresenter.setVisibility(false);
            mEdtAccount.setText(passwordLoginPresenter.getAccountText());
        }else {
            findViewById(R.id.ver_login_ly).setVisibility(View.GONE);
//            vTTT.setText(R.string.login_ttt_pwd);
            passwordLoginPresenter.setVisibility(true);
            passwordLoginPresenter.setAccountText(mEdtAccount.getText().toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }

    @NonNull
    @Override
    protected ImmersionBar createStatusBarConfig() {
        return super.createStatusBarConfig()
                // 指定导航栏背景颜色
                .statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont));
    }

    private void showLogoffDialog(){
        if (getIntent().getBooleanExtra("showLogoffDialog", false)){
            new ConfirmHintDialog.Builder(this)
                    //.setHint(getString(R.string.logoff_success))
                    .setContent(getString(R.string.logoff_success))
                    .setRightBtnText(getResources().getString(R.string.common_confirm))
                    .setHintIcon(R.attr.icon_remind_correct)
                    //.setCanceledOnTouchOutside(false)
                    .create()
                    .show();
        }
    }
}